package search

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"net/http"
	"novelDownlaod/config"
	"novelDownlaod/model"
	"strings"
)

func Search(keyword string) (model.SearchList,error) {
	res, err := http.Get(config.SearchUrl+keyword)
	if err != nil {
		fmt.Println("网络错误，请稍后重试")

	}
	defer res.Body.Close()
	if res.StatusCode != 200 {
		fmt.Println("status code error: %d %s", res.StatusCode, res.Status)
		return nil,err
	}
	doc, err := goquery.NewDocumentFromReader(res.Body)
	if err != nil {
		return nil,err
	}
	searches := model.SearchList{}
	doc.Find("body > div:nth-child(4) > div.list > div > ul > li").Each(func(i int, selection *goquery.Selection) {

			search := model.Search{}
			search.Index = i+1
			search.Author = selection.Find(".s").Text()
			search.BookName = selection.Find("a").Text()
			url, exits := selection.Find("a").Attr("href")
			if exits {
				search.Url = url
			}
			searches = append(searches, &search)
			search.Type=1


	})
	return searches,nil
}
func Search2(keyword string)(model.SearchList,error){
	res,err:=http.Get(config.SearchUrl2+keyword)
	if err != nil {
		return nil,err
	}
	defer res.Body.Close()
	doc,err:=goquery.NewDocumentFromReader(res.Body)
	if err != nil {
		return nil,err
	}
	searches := model.SearchList{}
	doc.Find("#waterfall >div").Each(func(i int, selection *goquery.Selection) {
		search := model.Search{}
		search.Index=i+1
		search.Author=selection.Find(".nickname").Text()
		search.BookName=selection.Find(".title").Text()
		url,exits:=selection.Find(".title").Find("a").Attr("href")
		if exits {
			fmt.Println(url)
			url=config.Url2+"/"+strings.Split(url,"/")[5]
			search.Url=url
		}
		search.Type=2
		searches=append(searches,&search)
	})
	return searches,nil
}
